const db = window.db;
const STORE_NAME = "formDatas";

function add(data) {
  return new Promise((resolve, reject) => {
    var request = db
      .transaction([STORE_NAME], "readwrite")
      .objectStore(STORE_NAME)
      .add(data);

    request.onsuccess = function (event) {
      console.log(event, "数据写入成功");
      resolve("数据写入成功");
    };

    request.onerror = function (event) {
      console.log(event, "数据写入失败");
      reject("数据写入失败");
    };
  });
}
function remove(id) {
  return new Promise((resolve, reject) => {
    var request = db
      .transaction([STORE_NAME], "readwrite")
      .objectStore(STORE_NAME)
      .delete(id);

    request.onsuccess = function (event) {
      console.log(event, "数据删除成功");
      resolve("数据删除成功");
    };
    request.onerror = function (event) {
      console.log(event, "数据删除失败");
      reject("数据删除失败");
    };
  });
}
function read(id) {
  return new Promise((resolve, reject) => {
    var objectStore = db.transaction([STORE_NAME]).objectStore(STORE_NAME);
    var request = objectStore.get(id);
    request.onerror = function (event) {
      console.log(event, "事务失败");
      reject(new Error("获取失败：" + id));
    };
    request.onsuccess = function (event) {
      if (request.result) {
        resolve(request.result);
      } else {
        console.log(event, "未获得数据记录");
        reject(new Error("未获得数据记录：" + id));
      }
    };
  });
}
function update(data) {
  return new Promise((resolve, reject) => {
    var request = db
      .transaction([STORE_NAME], "readwrite")
      .objectStore(STORE_NAME)
      .put(data);

    request.onsuccess = function (event) {
      console.log(event, "数据更新成功");
      resolve("数据更新成功");
    };

    request.onerror = function (event) {
      console.log(event, "数据更新失败");
      reject("数据更新失败");
    };
  });
}
function readAll() {
  return new Promise((resolve) => {
    var objectStore = db.transaction(STORE_NAME).objectStore(STORE_NAME);
    const data = [];
    objectStore.openCursor().onsuccess = function (event) {
      var cursor = event.target.result;
      if (cursor) {
        data.push({
          id: cursor.key,
          name: cursor.value.name,
          data: cursor.value.data,
        });
        cursor.continue();
      } else {
        console.log("没有更多数据了！");
        resolve(data);
      }
    };
  });
}

export default {
  add,
  remove,
  read,
  update,
  readAll,
};
